import sys
from pathlib import Path
from collections import Counter, defaultdict
from datetime import datetime

DURATION_LABELS = {"≤15秒", "≤1分钟", "≤5分钟", "＞5分钟"}


def read_first_line(p: Path) -> str:
    try:
        with p.open('r', encoding='utf-8') as f:
            return f.readline().strip()
    except Exception:
        return ''


def summarize_results(results_dir: Path):
    files = sorted(results_dir.glob('*.txt'))
    if not files:
        print(f"[错误] 未找到TXT: {results_dir}")
        sys.exit(1)

    # 统计首行分布
    first_lines = [read_first_line(p) for p in files]
    dist = Counter(first_lines)

    # 提取“视频时长”标签分布
    label_counts = Counter()
    unknown_counts = 0
    for line in first_lines:
        if line.startswith('视频时长:'):
            label = line.split(':', 1)[1].strip()
            if label in DURATION_LABELS:
                label_counts[label] += 1
            else:
                unknown_counts += 1
        else:
            unknown_counts += 1

    # 用修改时间分钟粒度的最大簇识别“本批次更新”的文件，其余推断为“跳过”
    minute_buckets = defaultdict(list)
    for p in files:
        try:
            ts = datetime.fromtimestamp(p.stat().st_mtime)
            ts_min = ts.replace(second=0, microsecond=0)
            minute_buckets[ts_min].append(p)
        except Exception:
            continue
    # 找到最大簇（假设为刚刚批量更新产生）
    max_cluster_minute, max_cluster_files = None, []
    if minute_buckets:
        max_cluster_minute = max(minute_buckets.items(), key=lambda kv: len(kv[1]))[0]
        max_cluster_files = minute_buckets[max_cluster_minute]
    skipped_files = [p for p in files if p not in set(max_cluster_files)]

    # 输出报告
    print(f"[总计] TXT 文件数: {len(files)}")
    print("[首行分布]")
    for line, cnt in dist.most_common():
        print(f"  {line} -> {cnt}")
    print("[分类标签分布]")
    for label in ["≤15秒", "≤1分钟", "≤5分钟", "＞5分钟"]:
        print(f"  {label} -> {label_counts.get(label, 0)}")
    if unknown_counts:
        print(f"  未识别/缺失 -> {unknown_counts}")
    print("[跳过文件推断]")
    print(f"  最大更新簇时间: {max_cluster_minute}")
    print(f"  推断跳过数: {len(skipped_files)}")
    for p in skipped_files:
        print(f"  {p.name}")


if __name__ == '__main__':
    results_dir = Path('results').resolve()
    summarize_results(results_dir)
